package ru.home.documentmanager.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Section;
import org.springframework.stereotype.Service;

import ru.home.documentmanager.service.DocService;

@Service("docService")
public class DocServiceImpl implements DocService {

    private static Pattern paramPattern = Pattern
            .compile("(?i)(\\$\\{([\\w\\.]+)\\})");

    private static HWPFDocument replaceText(HWPFDocument doc,
            Map<String, String> placeholders) {
        Range r1 = doc.getRange();

        for (int i = 0; i < r1.numSections(); ++i) {
            Section s = r1.getSection(i);
            for (int x = 0; x < s.numParagraphs(); x++) {
                Paragraph p = s.getParagraph(x);
                for (int z = 0; z < p.numCharacterRuns(); z++) {
                    CharacterRun run = p.getCharacterRun(z);
                    String text = run.text();
                    Matcher m = paramPattern.matcher(text);
                    while (m.find()) {
                        System.out.println("placeholder found: ");
                        String placeholder = m.group(0);
                        System.out.println(placeholder + " : " + m.group(1)
                                + " : " + m.group(2));
                        text.replace(placeholder, placeholders.get(placeholder));
                    }
                }
            }
        }
        return doc;
    }

    @Override
    public void replacePlaceholders(InputStream in, OutputStream out,
            Map<String, String> placeholders) throws IOException {
        HWPFDocument doc = new HWPFDocument(in);
        doc = replaceText(doc, placeholders);
        doc.write(out);
    }

}
